package com.foyekoo.project001.activity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.foyekoo.project001.R;
import com.foyekoo.project001.command.Command;
import com.foyekoo.project001.config.Config;
import com.foyekoo.project001.service.UsbHostService;
import com.foyekoo.project001.service.UsbService;
import com.foyekoo.project001.utils.DBUtil;
import com.foyekoo.project001.utils.DialogUtil;
import com.foyekoo.project001.utils.ReadThread;

import butterknife.BindView;
import butterknife.ButterKnife;

public class WelcomeActivity extends BaseActivity {
    @BindView(R.id.tv_Title)
    TextView tvTitle;
    @BindView(R.id.tv_Device)
    TextView tvDevice;


    private final int COMPANY_DELAY = 0;
    private final int USB_CONNECT = 1;
    private final int USB_UNCONNECT = 2;
    private final int USB_PERMISSION = 3;
    private final int USB_UNPERMISSION = 4;
    private final int USB_NAME = 5;
    private final int USB_PORT = 6;
    private UsbHostService usbHostService;

    private Message message = null;
    private Bundle bundle = null;

    private android.support.v4.app.DialogFragment dialogFragment;

    private void goToWaiting() {


        Intent intent = new Intent(this, WaitingActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP );
        startActivity(intent);
        finish();

    }


    @SuppressLint("HandlerLeak")
    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case COMPANY_DELAY:
                    finish();
                    startConnectDevice();

                    break;
                case USB_CONNECT:
                    tvDevice.setText("USB连接成功");
                    goToWaiting();
                    Command.IOConnectionConfirm(); //io 握手
                    Command.dataInit();
                    break;
                case USB_UNCONNECT:
                    finish();
                    break;
                case USB_PERMISSION:
                    //tvDevice.setText(tvDevice.getText().toString() + "\n" + msg.getData().getString(Config.ACTION_USB_PERMISSION));
                    break;
                case USB_UNPERMISSION:

                    //tvDevice.setText(tvDevice.getText().toString() + "\n" + msg.getData().getString(Config.ACTION_USB_UNPERMISSION));
                    break;
                case USB_NAME:
                    //tvDevice.setText(tvDevice.getText().toString() + "\n" + msg.getData().getString(Config.ACTION_USB_NAME));
                    break;
                case USB_PORT:
                    // tvDevice.setText(tvDevice.getText().toString() + "\n" + msg.getData().getString(Config.ACTION_USB_PORT));
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setScreen();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        ButterKnife.bind(this);

        registerReceiver(dataReceiver, new IntentFilter(ReadThread.ACTION_DATA_RECIEVE));
        registerReceiver(mReceiver, Config.getFilter());
        message = Message.obtain();
        bundle = new Bundle();
        handler.sendEmptyMessageDelayed(COMPANY_DELAY, 1000);
        startConnectDevice();
        DBUtil.initBillDB(); //初始化数据库
        DBUtil.initCoinNumDB();//初始化数据库
        setAudio();//设置音频

    }

    private void setAudio(){
        AudioManager man = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        man.setStreamVolume(AudioManager.STREAM_MUSIC, 255, AudioManager.FLAG_PLAY_SOUND);



    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
        unregisterReceiver(dataReceiver);
    }

    private BroadcastReceiver dataReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            byte[] data = intent.getByteArrayExtra(ReadThread.EXTRA_DATA);

            if (data[2] == 0x02) {
                if (data[3] == 0X01) {
                    dialogFragment = DialogUtil.showLoadingDialog(getSupportFragmentManager(), "电机校验中...");
                } else if (data[3] == 0x00) {
                    dialogFragment.dismiss();
                    tvDevice.setText("电机初始化成功");
                } else if (data[3] == 0x02) {
                    dialogFragment.dismiss();
                    tvDevice.setText("电机校验失败");
                }
            }
        }
    };


    public void setNavigationBarVisibility(boolean visible) {
        int flag = 0;
        if (!visible) {
            flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
        }

        getWindow().getDecorView().setSystemUiVisibility(flag);
    }

    //设置屏幕显示
    public void setScreen() {
        //去掉标题栏
        this.supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        //全屏显示
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //去掉虚拟按键
        setNavigationBarVisibility(false);
    }

    //连接设备，并显示连接信息
    private void startConnectDevice() {
        tvTitle.setVisibility(View.VISIBLE);
        tvDevice.setVisibility(View.VISIBLE);
        connectDevice();

    }

    //连接设备
    private void connectDevice() {
        Intent intent = new Intent(WelcomeActivity.this, UsbService.class);
        startService(intent);
    }

    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            usbHostService = ((UsbHostService.MyBinder) iBinder).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            usbHostService = null;
        }
    };

    //Handler消息传送数据
    private void handlerSendMsg(int what, String data, String config) {
        message.what = what;
        bundle.putString(config, data);
        message.setData(bundle);
        handler.sendMessage(message);
    }

    //接收广播，获取OBD连接状态及数据
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Config.ACTION_USB_CONNECT)) {
                handlerSendMsg(USB_CONNECT, intent.getStringExtra(Config.ACTION_USB_CONNECT), Config.ACTION_USB_CONNECT);
            } else if (action.equals(Config.ACTION_USB_UNCONNECT)) {
                handlerSendMsg(USB_UNCONNECT, intent.getStringExtra(Config.ACTION_USB_UNCONNECT), Config.ACTION_USB_UNCONNECT);
            } else if (action.equals(Config.ACTION_USB_PERMISSION)) {
                handlerSendMsg(USB_PERMISSION, intent.getStringExtra(Config.ACTION_USB_PERMISSION), Config.ACTION_USB_PERMISSION);
            } else if (action.equals(Config.ACTION_USB_UNPERMISSION)) {
                handlerSendMsg(USB_UNPERMISSION, intent.getStringExtra(Config.ACTION_USB_UNPERMISSION), Config.ACTION_USB_UNPERMISSION);
            } else if (action.equals(Config.ACTION_USB_NAME)) {
                handlerSendMsg(USB_NAME, intent.getStringExtra(Config.ACTION_USB_NAME), Config.ACTION_USB_NAME);
            } else if (action.equals(Config.ACTION_USB_PORT)) {
                handlerSendMsg(USB_PORT, intent.getStringExtra(Config.ACTION_USB_PORT), Config.ACTION_USB_PORT);
            }
        }
    };
}
